package com.example.xjt.safe;

import cn.hutool.core.collection.CollectionUtil;
import com.example.xjt.orm.menu.MenuDO;
import com.example.xjt.orm.menu.MenuRepo;
import com.example.xjt.orm.mr.MenuRole;
import com.example.xjt.orm.mr.MenuRoleRepo;
import com.example.xjt.orm.role.RoleDO;
import com.example.xjt.orm.role.RoleRepo;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 *
 * 这个类的作用，主要是根据用户传来的请求地址，分析出请求需要的角色
 */
@Component
public class CustomFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {



    @Autowired
    private MenuRepo menuRepo;
    @Autowired
    private MenuRoleRepo menuRoleRepo;
    @Autowired
    private RoleRepo roleRepo;

    AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        String requestUrl = ((FilterInvocation) object).getRequestUrl();
        List<MenuDO> menus = menuRepo.findAll();
        for (MenuDO menu : menus) {
            if (antPathMatcher.match(menu.getUrl(), requestUrl)) {

                //某菜单-准许访问的角色
                List<MenuRole> menuRoleList = menuRoleRepo.findAllByMid(menu.getId());
                if (CollectionUtil.isEmpty(menuRoleList)){
                    return org.springframework.security.access.SecurityConfig.createList("ROLE_LOGIN");
                }
                List<RoleDO> roles =  roleRepo.findAllById(menuRoleList.stream().map(MenuRole::getRid).distinct().collect(Collectors.toList()));
                String[] str = new String[roles.size()];
                for (int i = 0; i < roles.size(); i++) {
                    str[i] = roles.get(i).getRoleFlag();
                }

                // ["ROLE_X1","ROLE_X2","ROLE_X3"]
                return org.springframework.security.access.SecurityConfig.createList(str);
            }
        }
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
